// pages/sendGoods/sendGoods.js
var app = getApp()
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        show: false,
        loading:false,
        list: [],
        company: '',
        addressList: [],
        address: {},
        checkArr: [],
        goodsImg: {},
        freight: 0,
        arr: [],
        isFreight: true,
        curdate: new Date(),
        payType: 'wechat',
        freightf: null,
        orderNo: '',
        show1: false
    },
    getList: function() {
        wx.showToast({
            title: 'loading...',
            icon: 'loading',
            duration: 60000
        })
        var _this = this
        wx.request({
            url: app.globalData.url+'/v1/order/list',
            method: 'GET',
            data: {
                pagesize: 1000,
                current: 1,
                openid: app.globalData.openId,
                shop_state: 2
            },
            success: function(r) {
                if (r.data.code == 0) {
                    var arr = r.data.data.items.map(item => {
                        item.check = false
                        return item
                    })
                    console.log(arr)
                    _this.setData({
                        list: arr
                    })
                    wx.hideToast()
                }
            }
        })
    },

    getOrderNo() {
        var data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        var str = '';
        var date = new Date();
        var year = date.getFullYear();
        var mounth = date.getMonth() + 1;
        var date1 = date.getDate()
        for (var i = 0; i < 4; i++) {
            console.log(Math.floor(Math.random() * 10));
            var temp = Math.floor(Math.random() * 10);
            str += data[temp];
        }
        str += year;
        str += mounth;
        str += date1;
        for (var i = 0; i < 6; i++) {
            console.log(Math.floor(Math.random() * 10))
            var tepm = Math.floor(Math.random() * 10)
            str += data[tepm];
        }
        return str;
    },

    GetTime() {
        //在这里获取时间,如果是指定时间,清空购物车
        var dataTimes = new Date();
        //获取年月日
        var dataYear = dataTimes.getFullYear();
        var dataMonth = dataTimes.getMonth() + 1;
        var dataDay = dataTimes.getDate();
        if (dataMonth < 10) {
            dataMonth = '0' + dataMonth;
        };
        if (dataDay < 10) {
            dataDay = '0' + dataDay;
        };
        //  以下是获取时分秒
        var dataHours = dataTimes.getHours();
        var dataMinutes = dataTimes.getMinutes();
        var dataSeconds = dataTimes.getSeconds();
        this.setData({
            curdate: dataYear + "-" + dataMonth + "-" + dataDay + "-" + dataHours + '-' + dataMinutes + '-' + dataSeconds
        })

    },


    detailShow: function() {
        this.setData({
            show: !this.data.show
        })
    },
    detailShow1: function() {
        this.setData({
            show1: !this.data.show1
        })
    },
    //选择发货商品
    checked: function(e) {
        console.log('e----------',e)
        var index = e.currentTarget.dataset.index
        var item = 'list[' + index + '].check'
        this.setData({
            [item]: !this.data.list[index].check
        })
        var arr = this.data.list.filter(item => {
            return item.check
        })
        this.setData({
            checkArr: arr.map(item => {
                return item.oid
            })
        })
        if (arr.length == 0) {
            this.setData({
                company: ''
            })
        } else {
            this.setData({
                company: e.currentTarget.dataset.company
            })
        }
        console.log('company---------',this.data.company)
        console.log('checkArr----------',this.data.checkArr)
    },
    getAddressList: function() {
        var _this = this
        wx.request({
            url: app.globalData.url+'/v1/address/list',
            method: 'GET',
            data: {
                pagesize: 1000,
                current: 1,
                openid: app.globalData.openId
            },
            success: function(r) {
                if (r.data.code == 0) {
                    var arr = r.data.data.items.filter(item => {
                        return item.is_default == 2
                    })
                    if (!arr.length) {
                        arr = r.data.data.items
                    }
                    _this.setData({
                        addressList: r.data.data.items,
                        address: arr[0]
                    })
                } else {
                    wx.showToast({
                        title: r.data.data.message,
                        icon: 'none'
                    })
                }
            }
        })
    },
    // add: function(e) {
    //   var _this = this
    //   var index = e.currentTarget.dataset.index
    //   if (this.data.list[index].sendCount < this.data.list[index].count) {
    //     var item = 'list[' + index + '].sendCount'
    //     this.setData({
    //       [item]: this.data.list[index].sendCount + 1
    //     })
    //   }
    //   console.log(this.data.list)
    // },
    // reduce: function(e) {
    //   var index = e.currentTarget.dataset.index
    //   if (this.data.list[index].sendCount > 0) {
    //     var item = 'list[' + index + '].sendCount'
    //     this.setData({
    //       [item]: this.data.list[index].sendCount - 1
    //     })
    //   }
    //   console.log(this.data.list)
    // },
    changeAddress: function(e) {
        this.setData({
            address: e.currentTarget.dataset.address
        })
    },
    send: function() {
        var _this = this
        wx.showToast({
            title: 'loading...',
            icon: 'loading',
            duration: 60000
        })
        wx.request({
            url: app.globalData.url+'/v1/nihao/deliver',
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
                id: _this.data.checkArr.toString(),
                address_id: _this.data.address.id,
                openid: app.globalData.openId,
            },
            success: function(r) {
                r = r.data
                if (r.code == 0) {
                    wx.showToast({
                        title: r.data
                    })
                    setTimeout(function() {
                        wx.navigateBack({
                            delta: 1
                        })
                        wx.hideToast()
                    }, 2000)
                    
                } else {
                    wx.hideToast()
                    wx.showToast({
                        title: r.data.message,
                        icon: 'none'
                    })
                }
                _this.setData({
                    loading:false
                })
            },fail: (err) => {
                _this.setData({
                    loading:false
                })
            }
        })
    },
    confirm: function() {
        var _this = this
        _this.setData({
            ordercode: _this.getOrderNo()
        })
        if (!_this.data.checkArr.length) {
            wx.showToast({
                title: '请选择发货商品',
                icon: 'none'
            })
            return
        }
        var dnum = _this.data.list.filter(item => {
            return item.oid == _this.data.checkArr[0];
        });
        console.log('dnum---------',dnum)
        console.log('_this.data.checkArr.length---------',_this.data.checkArr.length)
        if (_this.data.checkArr.length < dnum[0].dnum) {

            wx.showModal({
                title: '提示',
                content: `${dnum[0].dprice}元运费,${ dnum[0].dnum }件起包邮,`,
                success(res) {
                    if (res.confirm) {
                        var temp = { data: _this.data.checkArr }
                        _this.setData({
                            isFreight: false,
                            freightf: dnum[0].dprice
                        });

                    } else if (res.cancel) {
                        console.log('用户点击取消')
                    }
                }
            })
        } else {
            _this.send()
        }
        console.log(_this.data.isFreight);
    },

    closeFre() {
        this.setData({
            isFreight: true,
        });
    },


    changePayType(e) {
        this.setData({
            payType: e.currentTarget.dataset.type
        })
    },
    //点击支付
    createOrderf: function() {
        var _this = this
        _this.setData({
            loading:true
        })
        if (_this.data.payType == 'wechat') {
            //微信支付
            wx.request({
                url: app.globalData.url+'/v1/freight/pay',
                method: 'POST',
                header: {
                    'content-type': 'application/x-www-form-urlencoded'
                },
                data: {
                    id: _this.data.checkArr,
                    orderName: Number(_this.data.freightf),
                    openid: app.globalData.openId,
                    ordercode: _this.data.ordercode
                },
                success: function(r) {
                    if (r.data.code == 0) {
                        // console.log(r);
                        // // _this.beforePay(r.data.data.package)
                        // _this.pay(r.data.data.package)
                        _this.payf(r.data.data.package)

                    } else {
                        wx.showToast({
                            title: r.data.data.message,
                            icon: 'none',
                            duration: 4000
                        })
                        _this.setData({
                            loading:false
                        })
                    }
                }
            })
        } else {
            //余额支付
            wx.request({
                url: app.globalData.url+'/v1/payment/freight',
                method: 'POST',
                header: {
                    'content-type': 'application/x-www-form-urlencoded'
                },
                data: {
                    openid: app.globalData.openId,
                    id: _this.data.checkArr,
                    ordercode: _this.data.ordercode
                },
                success: function(r) {
                    r = r.data
                    if (r.code == 0) {
                        wx.showToast({
                            title: r.data
                        })
                        _this.send();
                        setTimeout(function() {
                            wx.redirectTo({
                                url: '/pages/order/order',
                            })
                            wx.hideToast()
                        }, 2000)
                    } else {
                        wx.hideToast()
                        wx.showToast({
                            title: r.data.message,
                            icon: 'none'
                        })
                        _this.setData({
                            loading:false
                        })
                    }
                }
            })
        }
    },
    beforePayf: function(data) {
        var _this = this
        wx.request({
            url: app.globalData.url+'/v1/wechat/pay',
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
                uid: data.uid,
                id: data.id,
                orderName: 'WOWSURPRISE有惊喜'
            },
            success: function(r) {
                _this.payf(r.data.data.package, data.id)
            }
        })
    },
    //确认支付
    payf: function(data) {
        var _this = this
        wx.requestPayment({
            timeStamp: data.timeStamp,
            nonceStr: data.nonceStr,
            package: data.package,
            signType: 'MD5',
            paySign: data.paySign,
            success(res) {
                console.log(res);
                _this.sendf();
            },
            fail(res) {
                wx.showToast({
                    icon: 'none',
                    title: '用户取消支付',
                })
                _this.setData({
                    loading:false
                })
            }
        })
    },
    //支付成功后跳转发货
    sendf: function() {
        var _this = this
        wx.showToast({
            title: 'loading...',
            icon: 'loading',
            duration: 60000
        })
        wx.request({
            url: app.globalData.url+'/v1/nihao/deliver',
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
                id: _this.data.checkArr.toString(),
                address_id: _this.data.address.id,
                openid: app.globalData.openId,
            },
            success: function(r) {
                r = r.data
                if (r.code == 0) {
                    Toast.success(r.data);
                    wx.redirectTo({
                        url: '/pages/order/order',
                    })
                    wx.hideToast()
                } else {
                    wx.hideToast()
                    wx.showToast({
                        title: r.data.message,
                        icon: 'none'
                    })
                }
                _this.setData({
                    loading:false
                })
            },fail: (err) => {
                _this.setData({
                    loading:false
                })
            }
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.setData({
            goodsImg: app.globalData.goodsImg,
            payTag: options.pay
        })

        this.GetTime();

        // this.setData({
        //     freightf: options.data,
        //     arr: JSON.parse(options.arr).data,
        //     addressId: options.addressId
        // })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        this.getList()
        this.getAddressList()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})